<template>
  <div class="footer-bar">
    <div class="footer-left time-vertical u-f-ac">
      <span class="time-hms">{{ hms }}</span>
      <span class="time-year">{{ year }}</span>
      <span class="time-md">{{ md }}</span>
    </div>
    <div class=" u-f-ajsb bag" style="width: 200px;margin-left: 20px;">
      <div class="icon" :class="{ acvite: route.path === '/' }" @click="goHome">
        <i class="iconfont icon-home "></i>
        <span v-if="badge.home" class="icon-badge">{{ badge.home }}</span>
      </div>
      <div class="icon" :class="{ acvite: route.path === '/member' }" @click="goMember">
        <i class="iconfont icon-renqun"></i>
        <span v-if="badge.member" class="icon-badge"></span>
      </div>
      <div class="icon" :class="{ acvite: route.path === '/report' }" @click="goReport">
        <i class="iconfont icon-xiangmuzhuanyi"></i>
        <span v-if="badge.xiangmuzhuanyi" class="icon-badge">{{ badge.xiangmuzhuanyi }}</span>
      </div>
      <div class="icon" :class="{ acvite: route.path === '/bag' }" @click="goBag">
        <i class="iconfont icon-pocketkoudai"></i>
        <span v-if="badge.pocketTaskItemCount" class="icon-badge">{{ badge.pocketTaskItemCount }}</span>
      </div>
    </div>
    <div style="margin-left: 50px;" v-if="userInfo">{{ userInfo.name || '历史用户' }}</div>
    <div v-if="iotEnable" class="u-f-ajsb" style="width: 120px;margin-left: 100px;">
      <div class="icon" @click="showOrder">
        <i class="iconfont icon-dingdan"></i>
        <span v-if="badge.onlineTaskCount" class="icon-badge">{{ badge.onlineTaskCount }}</span>

      </div>
      <div class="icon" @click="showIotHis">
        <i class="iconfont icon-dingdanshijian"></i>
        <span v-if="badge.historyTaskCount" class="icon-badge">{{ badge.historyTaskCount }}</span>
      </div>
    </div>
    <div class="footer-center">
      <slot></slot>
    </div>
    <div class="footer-right u-f-ajsb">
      <div class="user-menu-container" @click="toggleUserMenu">
        <div style="width: 750px;margin-right: 90px;">
          {{ email }}
        </div>

        <!-- 用户菜单弹窗 -->
        <div v-if="showUserMenu" class="user-menu" @click.stop>
          <div class="user-menu-item" @click="changePassword">
            <el-icon>
              <Edit />
            </el-icon>
            <span>{{ $t('components.foot.changePassword') }}</span>
          </div>
          <div class="user-menu-item" @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>{{ $t('components.foot.logout') }}</span>
          </div>
        </div>
      </div>

      <div class="icon" @click="showPassWord" :class="{ acvite: !isLock }">
        <i class="iconfont icon-suoding" v-if="!isLock"></i>
        <i class="iconfont icon-jiesuo" v-else></i>
      </div>
      <div class="icon" @click="showSound">
        <i class="iconfont icon-shengyin"></i>
      </div>
      <div class="icon" :class="{ acvite: route.path === '/setting' }" @click="goSetting">
        <i class="iconfont icon-shezhi"></i>
      </div>
      <div class="icon" @click="exit">
        <i class="iconfont icon-guanji"></i>
      </div>
      <!-- 右侧可扩展 -->
    </div>
    <Password @unlock="unlock" ref="passwordRef" />
    <Sound ref="soundRef" />
    <ChangePassword ref="changePasswordRef" />
    <Dialog ref="dialogRef">
      <div>
        <div style="color: #000;font-size: 22px;margin-top: 20px;">
          {{ $t('components.foot.confirmExit') }}
        </div>
        <div class="dialog-btn" style="margin-top: 70px;">
          <button class="dialog-confirm" @click="doExit">{{ $t('common.confirm') }}</button>
          <button class="dialog-cancel" @click="dialogRef.close()">{{ $t('common.cancel') }}</button>
        </div>
      </div>

    </Dialog>
    <Dialog ref="orderRef">
      <div>
        <div style="color: #000;font-size: 22px;margin-top: 20px;">
          {{ hisType == 'history' ? $t('components.foot.noHistoryTasks') : $t('components.foot.noAssignedTasks') }}
        </div>
        <div class="dialog-btn" style="margin-top: 70px;">
          <button class="dialog-confirm" @click="orderRef.close()">{{ $t('common.confirm') }}</button>
        </div>
      </div>
    </Dialog>
    <Dialog ref="errorRef">
      <div>
        <div style="color: #000;font-size: 22px;margin-top: 20px;">
          {{ $t('components.foot.serviceError') }}
        </div>
        <div class="dialog-btn" style="margin-top: 70px;">
          <button class="dialog-confirm" @click="doExit">{{ $t('common.confirm') }}</button>
        </div>
      </div>
    </Dialog>
    <IotHis ref="iotHisRef" :list="iotHisList" @switchTask="showIotHis" @pageChange="handlePageChange" :hisType="hisType" />
  </div>
</template>

<script setup>
import { Edit, SwitchButton } from '@element-plus/icons-vue'
import { ElLoading } from 'element-plus'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import ChangePassword from './ChangePassword.vue'
import Dialog from './Dialog.vue'
import IotHis from './IotHis.vue'
import Password from './Password.vue'
import Sound from './Sound.vue'

// 使用备用翻译系统
let t = (key) => key
let setLang = (newLang) => { }

// 创建响应式的翻译函数
const translationVersion = ref(0)
const $t = (key) => {
  // 依赖translationVersion来触发响应式更新
  translationVersion.value
  return t(key)
}

// 初始化翻译函数
const initTranslations = async () => {
  try {
    const fallback = await import('../utils/i18n-fallback')
    t = fallback.t
    setLang = (newLang) => {
      fallback.setLang(newLang)
      translationVersion.value++
    }
    // 监听语言变化事件
    window.addEventListener('language-changed', () => {
      translationVersion.value++
      // 语言切换时立即更新时间格式
      updateTime()
    })
  } catch (error) {
    console.warn('Failed to load i18n fallback:', error)
  }
}
const hms = ref('')
const year = ref('')
const md = ref('')
let timer = null
const dialogRef = ref(null)
const iotHisRef = ref(null)
const router = useRouter()
const errorRef = ref(null)
const route = useRoute()
const passwordRef = ref(null)
const soundRef = ref(null)
const changePasswordRef = ref(null)
const badge = ref({
  home: 0,
  member: 0,
  xiangmuzhuanyi: 0, // 示例，显示1
  pocketkoudai: 0
})
const email = ref('')

const iotHisList = ref([])
const userInfo = ref(JSON.parse(localStorage.getItem('user') || '{}'))
const orderRef = ref(null)
const isLock = ref(false)
const hisType = ref('history')
const showUserMenu = ref(false)
const iotEnable = ref(true) // IoT 开关状态
const goBag = () => {
  router.push('/bag')
}
const showOrder = () => {
  hisType.value = 'order'
  // 重置页码
  iotHisRef.value.resetPage()
  loadOrderData(1)
}

// 加载订单数据
const loadOrderData = (page) => {
  const loadingEl = ElLoading.service({
    lock: false,
    text: $t('components.foot.loading'),
    background: 'rgba(0, 0, 0, 0)',
  })
  window.request?.('/task/list', {
    method: 'GET', params: {
      patientId: userInfo.value.id,
      pageSize: 7,
      pageNum: page
    }
  }).then(res => {
    iotHisList.value = []
    loadingEl.close()
    console.log(res);
    if (res.rows && res.rows.length == 0) {
      orderRef.value.open()
      return
    }
    iotHisList.value = res.rows
    // 更新总数
    if (res.total !== undefined) {
      iotHisRef.value.updateTotal(res.total)
    }
    // 更新当前页码
    console.log('更新当前页码:', page)
    iotHisRef.value.updateCurrentPage(page)
    iotHisRef.value.open()

  }).catch(err => {
    loadingEl.close()
  })
}
const showPassWord = () => {
  if (isLock.value) {
    passwordRef.value.open()
  } else {
    router.push('/')
    isLock.value = true
    localStorage.setItem('isLock', 'true')
  }

}
const unlock = () => {
  isLock.value = false
  localStorage.setItem('isLock', 'false')
}
const showIotHis = () => {
  if (isLock.value) {
    window.messageRef?.show($t('components.foot.lockedState'), 'error')
    passwordRef.value.open()
    return
  }
  hisType.value = 'history'
  // 重置页码
  iotHisRef.value.resetPage()
  loadIotHisData(1)
}

// 加载IoT历史数据
const loadIotHisData = (page) => {
  const loadingEl = ElLoading.service({
    lock: false,
    text: $t('components.foot.loading'),
    background: 'rgba(0, 0, 0, 0)',
  })
  window.request?.('/task/historyList', {
    method: 'GET', params: {
      patientId: userInfo.value.id,
      pageSize: 7,
      pageNum: page
    }
  }).then(res => {
    iotHisList.value = []
    loadingEl.close()
    console.log(res);
    if (res.rows && res.rows.length == 0) {
      orderRef.value.open()
      return
    }
    iotHisList.value = res.rows
    // 更新总数
    if (res.total !== undefined) {
      iotHisRef.value.updateTotal(res.total)
    }
    // 更新当前页码
    console.log('更新当前页码:', page)
    iotHisRef.value.updateCurrentPage(page)
    iotHisRef.value.open()

  }).catch(err => {
    loadingEl.close()
  })
}

// 处理分页事件
const handlePageChange = (params) => {
  console.log('分页事件:', params)
  if (hisType.value === 'history') {
    loadIotHisData(params.page)
  } else if (hisType.value === 'order') {
    loadOrderData(params.page)
  }
}
const goReport = () => {
  if (isLock.value) {
    window.messageRef?.show($t('components.foot.lockedState'), 'error')
    passwordRef.value.open()
    return
  }
  router.push('/report')
}

const exit = () => {
  if (isLock.value) {
    window.messageRef?.show($t('components.foot.lockedState'), 'error')
    passwordRef.value.open()
    return
  }
  dialogRef.value.open()
}
const goSetting = () => {
  if (isLock.value) {
    window.messageRef?.show($t('components.foot.lockedState'), 'error')
    passwordRef.value.open()
    return
  }
  router.push('/setting')
}
const goMember = () => {
  if (isLock.value) {
    window.messageRef?.show($t('components.foot.lockedState'), 'error')
    passwordRef.value.open()
    return
  }
  router.push('/member')
}
const goHome = () => {
  router.push('/')
}
function updateTime() {
  const now = new Date()
  hms.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`

  // 获取多语言日期格式
  const yearSuffix = $t('components.foot.dateFormat.year')
  const monthSuffix = $t('components.foot.dateFormat.month')
  const daySuffix = $t('components.foot.dateFormat.day')

  // 根据语言格式化日期
  if (yearSuffix) {
    // 中文格式：2024年
    year.value = `${now.getFullYear()}${yearSuffix}`
    md.value = `${String(now.getMonth() + 1).padStart(2, '0')}${monthSuffix}${String(now.getDate()).padStart(2, '0')}${daySuffix}`
  } else {
    // 英文格式：2024 或者不显示年份后缀
    year.value = `${now.getFullYear()}`
    // 英文格式：12/25 (月/日)
    md.value = `${String(now.getMonth() + 1).padStart(2, '0')}${monthSuffix}${String(now.getDate()).padStart(2, '0')}`
  }
}

const showSound = () => {
  if (soundRef.value.visible) {
    soundRef.value.close()
  } else {
    soundRef.value.open()
  }
}

const doExit = () => {
  // 调试模式下不关机
  if (import.meta.env.DEV) {
    window.messageRef?.show('调试模式下不执行关机操作', 'info')
    return
  }

  // Electron 环境下关机
  if (window.electron && window.electron.ipcRenderer) {
    window.electron.ipcRenderer.invoke('shutdown-computer')
  } else {
    // 浏览器环境下提示
    window.messageRef?.show('此功能仅在桌面应用中可用', 'warning')
  }
}
function handleUserChange(e) {
  userInfo.value = e.detail
  // 用户变化时立即更新，不使用防抖
  let user = localStorage.getItem('user')
  if (user) {
    window.request?.('/task/getCount/' + userInfo.value.id, { method: 'GET', }).then(res => {
      console.log('用户变化时 getNumber 执行:', res);
      badge.value = res
    })

    window.request?.('/system/patient/switchPatient/'+userInfo.value.id, { method: 'GET',params:{
    patientId: user.id,
    
  } }).then(res => {
    console.log(res);
    
  })


  }
}

function handleIotStatusChange(e) {
  console.log('IoT 状态变化:', e.detail.iotEnable)
  iotEnable.value = e.detail.iotEnable
}
// 全局防抖变量，确保整个应用只有一个请求在执行
let globalGetNumberTimer = null
let isGetNumberRequesting = false

function getNumber() {
  console.log('🔄 getNumber 被调用，当前防抖状态:', !!globalGetNumberTimer, '请求状态:', isGetNumberRequesting)
  
  // 如果已经有定时器在运行，清除它
  if (globalGetNumberTimer) {
    console.log('⏰ 清除之前的防抖定时器')
    clearTimeout(globalGetNumberTimer)
  }
  
  // 如果正在请求中，直接返回
  if (isGetNumberRequesting) {
    console.log('⏳ 已有请求在执行中，跳过')
    return
  }
  
  // 设置防抖，300ms内只执行最后一次
  globalGetNumberTimer = setTimeout(() => {
    console.log('🚀 执行 getNumber 请求')
    isGetNumberRequesting = true
    
    let user = localStorage.getItem('user')
    if (user) {
      window.request?.('/task/getCount/' + userInfo.value.id, { method: 'GET', }).then(res => {
        console.log('✅ getNumber 请求成功:', res);
        badge.value = res
        isGetNumberRequesting = false
      }).catch(err => {
        console.error('❌ getNumber 请求失败:', err)
        isGetNumberRequesting = false
      })
    } else {
      isGetNumberRequesting = false
    }
    
    globalGetNumberTimer = null
    console.log('🏁 getNumber 防抖定时器完成')
  }, 300)
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  if (showUserMenu.value && !event.target.closest('.user-menu-container')) {
    showUserMenu.value = false
  }
}
const verification = () => {
  window.request?.('/verification', {
    method: 'GET',
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
    errorRef.value.open()

  })
}
let timer2 = null
let timer3 = null
onMounted(async () => {
  await initTranslations()
  email.value = localStorage.getItem('email')

  // 初始化 IoT 状态
  const savedIotEnable = localStorage.getItem('iotEnable')
  if (savedIotEnable !== null) {
    iotEnable.value = savedIotEnable === 'true'
  }

  updateTime()
  getNumber()
  verification()
  timer2 = setInterval(getNumber, 10000)
  timer3 = setInterval(verification, 60000)
  timer = setInterval(updateTime, 1000)
  window.addEventListener('bg-change', getNumber)
  window.addEventListener('user-changed', handleUserChange)
  window.addEventListener('iot-status-changed', handleIotStatusChange)
  document.addEventListener('click', handleClickOutside)

})

onUnmounted(() => {
  console.log('📤 Foot 组件卸载，清理资源')
  clearInterval(timer)
  clearInterval(timer2)
  clearInterval(timer3)
  
  // 清理全局防抖定时器
  if (globalGetNumberTimer) {
    clearTimeout(globalGetNumberTimer)
    globalGetNumberTimer = null
  }
  isGetNumberRequesting = false

  // 移除事件监听器
  window.removeEventListener('bg-change', getNumber)
  window.removeEventListener('user-changed', handleUserChange)
  window.removeEventListener('iot-status-changed', handleIotStatusChange)
  document.removeEventListener('click', handleClickOutside)
})

// 切换用户菜单显示状态
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value
}

// 修改密码
const changePassword = () => {
  showUserMenu.value = false
  changePasswordRef.value.open()
}

// 退出登录
const logout = () => {
  showUserMenu.value = false
  window.request?.('/logout', { method: 'POST', }).then(res => {

    })
  // 清除用户信息
  localStorage.removeItem('user')
  localStorage.removeItem('token')
  
  // 跳转到登录页
  router.push('/login')
}

</script>

<style scoped>
.icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.acvite {
  background-color: #fff;
  color: var(--theme-secondary);
  border-radius: 50%;

}

.iconfont {

  font-size: 30px;
}

.footer-bar {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  height: 65px;
  background: var(--theme-secondary);
  color: #fff;
  display: flex;
  align-items: center;
  z-index: 1000;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}

.footer-left.time-vertical {
  flex: 0 0 80px;
  padding-left: 24px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100%;
}

.time-hms {
  font-size: 13px;
  font-weight: bold;
  line-height: 1.2;
}

.time-year {
  font-size: 12px;
  margin: 2px 0;
  line-height: 1.2;
}

.time-md {
  font-size: 13px;
  line-height: 1.2;
}

.footer-center {
  flex: 1;
  text-align: center;
}

.footer-right {
  text-align: right;
  padding-right: 24px;
  width: 16vw;
}

.password-panel {
  margin: 24px auto 0 auto;
  width: 320px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.password-display {
  width: 100%;
  height: 40px;
  background: #f6fafd;
  border: 1.5px solid #e0e6ed;
  border-radius: 8px;
  margin-bottom: 18px;
  font-size: 22px;
  color: #333;
  letter-spacing: 8px;
  text-align: center;
  line-height: 40px;
  box-sizing: border-box;
}

.keypad {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 14px;
}

.key {
  height: 44px;
  font-size: 20px;
  border: none;
  border-radius: 8px;
  background: #eaf3fa;
  color: #333;
  cursor: pointer;
  transition: background 0.2s;
}

.key:active {
  background: #b6d6f6;
}

.dialog-btn {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 32px;
}

.dialog-confirm {
  min-width: 90px;
  background: var(--theme-secondary);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}

.dialog-confirm:hover {
  background: #1e5e92;
}

.dialog-cancel {
  min-width: 90px;
  background: #f3f3f3;
  color: #888;
  border: none;
  border-radius: 8px;
  font-size: 18px;
  padding: 8px 0;
  cursor: pointer;
  transition: background 0.2s;
}

.dialog-cancel:hover {
  background: #e0e0e0;
}

.icon-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  min-width: 22px;
  height: 22px;
  background: #a01623;
  color: #fff;
  border-radius: 50%;
  font-size: 15px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #fff;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.10);
}

.user-menu-container {
  position: relative;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  transition: background 0.2s;
}

.user-menu-container:hover {
  /* background: rgba(255, 255, 255, 0.1); */
}

.user-menu {
  position: absolute;
  bottom: 50px;
  right: 0;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  padding: 8px 0;
  min-width: 140px;
  z-index: 9999;
  animation: menuFadeIn 0.2s ease-out;
}

@keyframes menuFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.user-menu-item {
  display: flex;
  align-items: center;
  padding: 12px 25px;
  color: #333;
  cursor: pointer;
  transition: background 0.2s;
  font-size: 14px;
}

.user-menu-item:hover {
  background: #f5f5f5;
}

.user-menu-item i {
  font-size: 16px;
  margin-right: 8px;
  width: 16px;
}

.user-menu-item span {
  flex: 1;
}
</style>
